#!/usr/bin/perl
#
# CGI: Move records from one place to another.
#

#
use FileTable;
use Validate::Persons;
use Validate::Places;
use POSIX;
use Counter::CGI;
use CGI::Carp;
# Counter specific
use ErrorForm;

require "lib/isemail.pl";

$] > 5.008 && binmode(STDOUT, ":utf8"); # set web page output to utf-8
$prefix = "db";

# Parse the entry
$entry = new Counter::CGI;

$persons = FileTable::open("${prefix}/persons", O_RDWR);
$places = FileTable::open("${prefix}/places", O_RDWR);
$placename = $entry->param("place");
$place = $places->getbykey("name", $placename);
if (!$place) {
    errorForm("No such place as $placename");
}
print <<EoF;
Content-type: text/html; charset="utf-8"

<html><head>
</head><body>
EoF

$reccount = 0;
$movecount = 0;
for $rec ($persons->select("placeid = ?", $place->{name})) {
    ++ $reccount;
    $recclean = $persons->getclean($rec->key());
    if (!$rec || !$recclean) {
	errorForm("Record $key: Clean not found");
    }
    $newplace = Validate::Places::findplace($rec);
    if (!$newplace) {
	warn "No place found for $key\n";
	print "$key did not find a place<br>\n";
    } elsif ($newplace->{name} ne $recclean->{placeid}) {
	my $oldplace = $recclean->{placeid};
	my $newname = $newplace->{name};
	$rec->clean();
	print "$key cleaned from $oldplace to $newname<br>\n";
    }
    if ($newplace->{name} ne $place->{name}) {
	print "Moving $key from ", $place->{name}, " to ",
		$newplace->{name}, "<br>\n";
	++ $movecount;
    }	
}
print "$reccount records, $movecount moves<br>\n";
print "</body></html>\n";

